import { createStore } from 'vuex'
import {homeReq} from '@/api/home.js';

const store = createStore({
    state() {
        return {
            // 登录用户
            realName:'',
            // 用户头像
            avatar:'',
            // 左侧菜单栏
            leftMenu: [],
            // 按钮权限
            buttonPerms: [],
            // 全局路由
            routers:[],
        }
    },
    mutations: {
        setRealName(state, realName) {
            state.realName = realName
        },
        setLeftMenu(state, leftMenu) {
            state.leftMenu = leftMenu
        },
        setButtonPerms(state, buttonPerms) {
            state.buttonPerms = buttonPerms
        },
        setAvatar(state, avatar) {
            state.avatar = avatar
        },
        setRouters(state, routers) {
            state.routers = routers
        },
    },
    actions: {
        getHome(context) {
            return new Promise((resolve, reject) => { // 返回Promise
              homeReq().then(res => {
                if(res.code == 200){
                  context.commit('setAvatar', res.data.avatar)
                  context.commit('setLeftMenu', res.data.menuTree)
                  context.commit('setButtonPerms', res.data.buttons)
                  context.commit('setRouters', res.data.routers)
                  context.commit('setRealName', res.data.realName)
                  resolve() // 成功时resolve
                } else {
                  reject(res.message) // 失败时reject
                }
              }).catch(err => reject(err))
            })
          }
    }
})

export default store